<?php
namespace app\controller;

use app\BaseController;
use think\facade\Request;
use think\facade\Db;
use think\Exception;

class Branch extends BaseController
{
    //获取分店列表
    public function get_branchinfo()
    {
        $userId = $this->request->auth['data']->user->user_id;
        $current_page = Request::param('current_page');
        $page_size = Request::param('page_size');

        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        try {
            $branch_info = Db::table('branch')
                ->where('branch_company_id', $companyId)
                ->page($current_page, $page_size)
                ->select();


            $count = Db::table('branch')
                ->where('branch_company_id', $companyId)
                ->count();






            return json([
                'code' => 200,
                'msg' => '获取分店列表成功',
                'data' => [
                    'data' => $branch_info,
                    'total' => $count
                ]
            ]);
        } catch (Exception $e) {
            return json([
                'code' => 500,
                'msg' => '获取分店列表失败',
                'data' => [
                    'error' => $e->getMessage()
                ]
            ]);
        }


    }

    //新增分店
    public function insert_branchinfo()
    {
        $userId = $this->request->auth['data']->user->user_id;

        $data=Request::param('data');

        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        // 验证参数
        if (!is_array($data)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }



        try {
            $branch_info = Db::table('branch')
                ->where('branch_company_id', $companyId)
                ->where('branch_name', $data['branch_name'])
                ->find();

            if ($branch_info) {
                return json([
                    'code' => 400,
                    'msg' => '分店名称已存在',
                ]);
            }

            $insert_data = [
                'branch_company_id' => $companyId,
                'branch_name' => $data['branch_name'],
                'branch_address' => $data['branch_address'],
                'branch_phone' => $data['branch_phone'],
                'branch_contacts'=> $data['branch_contacts'],
            ];
            if (Db::table('branch')->insert($insert_data)) {
                return json([
                    'code' => 200,
                    'msg' => '新增分店成功',
                ]);
            } else {
                return json([
                    'code' => 500,
                    'msg' => '新增分店失败',
                ]);
            }
            } catch (Exception $e) {
                return json([
                    'code' => 500,
                    'msg' => '新增分店失败',
                    'data' => [
                        'error' => $e->getMessage()
                    ]
                ]);

            }




    }

    //修改分店
    public function update_branchinfo()
    {
        $branch_id=Request::param('id');

        $data=Request::param('data');

        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        if (!is_array($data)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        try {
            //开启事务
            Db::startTrans();

            //判断除了当前分店名称外，是否存在相同的分店名称
            $branch_info = Db::table('branch')
                ->where('branch_id', '<>', $branch_id)
                ->where('branch_name', $data['branch_name'])
                ->where('branch_company_id', $companyId)
                ->find();

            if ($branch_info) {
                return json([
                    'code' => 400,
                    'msg' => '分店名称已存在',
                ]);
            }
            $res=Db::table('branch')->where('branch_id', $branch_id)->update($data);
            if ($res) {
                //提交事务
                Db::commit();
                return json([
                    'code' => 200,
                    'msg' => '修改分店成功',
                ]);

            } else {
                return json([
                    'code' => 500,
                    'msg' => '修改分店失败',
                ]);
            }
            } catch (Exception $e) {
                //回滚事务
                Db::rollback();
                return json([
                    'code' => 500,
                    'msg' => '修改分店失败',
                    'data' => [
                        'error' => $e->getMessage()
                    ]
                ]);
        }


    }

    //删除分店
    public function Delete_BranchInfo()
    {
        $branch_id=Request::param('id');

        try {
            if (Db::table('branch')->where('branch_id', $branch_id)->delete($branch_id)) {
                return json([
                    'code' => 200,
                    'msg' => '删除分店成功',
                ]);
            } else {
                return json([
                    'code' => 500,
                    'msg' => '删除分店失败',
                ]);
            }
            } catch (Exception $e) {
            Db::rollback();

            if($e->getCode()==10501)
            {
                return json(['code' => 500, 'msg' => '该分店下已存在单据，无法删除']);
            }
            
                return json([
                    'code' => 500,
                    'msg' => '删除分店失败',
                    'data' => [
                        'error' => $e->getMessage()
                    ]
                ]);
        }
    }
}